﻿
/// <reference path="/Scripts/jquery-1.4.1.js"/>

function createTheaterIndexMap(mapId) {
    var map;
    var mode = "browse";
    var latitude;
    var longitude;
    var displayName = "none";
    var existingTheatersLayer;
    var newTheatersLayer;
    return {
        init: function (mapId, latitudeId, longitudeId, displayNameId) {
            var that = this;
            this.latitude = $(latitudeId);
            this.longitude = $(longitudeId);
            this.displayName = $(displayNameId);
            this.map = new VEMap(mapId);
            this.map.LoadMap();
            this.existingTheatersLayer = new VEShapeLayer();
            this.map.AddShapeLayer(this.existingTheatersLayer);
            this.newTheatersLayer = new VEShapeLayer();
            this.map.AddShapeLayer(this.newTheatersLayer);
            this.map.AttachEvent("onmouseup", function (e) {
                that.updatePosition(e);
            });
        },

        attachResizeHandler: function (window) {
            $(window).resize(function () { });
        },

        resizeMap: function () {
        },

        getTheaters: function () {
            var that = this;
            $.getJSON("/Theater/IndexData", null, function (data) {
                for (var i in data) {
                    var theaterShape = new VEShape(VEShapeType.Pushpin, [new VELatLong(data[i].latitude, data[i].longitude)]);
                    theaterShape.SetTitle(data[i].name);
                    theaterShape.SetDescription(data[i].description);
                    that.existingTheatersLayer.AddShape(theaterShape);
                }
            });
        },

        updatePosition: function (e) {
            var that = this;
            var latLong = this.map.PixelToLatLong(new VEPixel(e.mapX, e.mapY));
            var url = "Services/ReverseGeocode?latitude={lat}&longitude={long}".replace("{lat}", latLong.Latitude).replace("{long}", latLong.Longitude);
            $.getJSON(url, null, function (data) {
                that.newTheatersLayer.DeleteAllShapes();

                if (data.Results != null && data.Results.length) {
                    $(that.latitude).attr("value", data.Results[0].Locations[0].Latitude);
                    $(that.longitude).attr("value", data.Results[0].Locations[0].Longitude);
                    $(that.displayName).attr("value", data.Results[0].DisplayName);
                }
                for (var i in data.Results) {
                    var result = data.Results[i];
                    var shape = new VEShape(VEShapeType.Pushpin, [new VELatLong(result.Locations[0].Latitude, result.Locations[0].Longitude)]);
                    shape.SetTitle(result.DisplayName);
                    shape.SetDescription(result.DisplayName);
                    that.newTheatersLayer.AddShape(shape);
                }
            });
        }
    };
}
